<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>文件上传</title>
</head>
<body>

<div align="center">
  <input type="file" id="pic" name="pic"/>
  <input type="button" value="上传图片" onclick="uploadFile()" />
</div>
<div id="progressBar" style="padding:0px;border:solid black 0px;visibility:hidden">
  <table width="300" border="0" cellspacing="0" cellpadding="0" align="center">
    <tr>
      <td align="center" id="progressPersent">0%</td>
    </tr>
    <tr>
      <td>
        <!-- 黑色边框部分 -->
        <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#000000">
          <tr>
            <td>
              <!-- 红色部分 -->
              <table width="1%" border="0" cellspacing="0" cellpadding="0"
                     bgcolor="#FF0000" id="progress">
                <tr>
                  <td>&nbsp;</td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td align="center" id="complete">completed</td>
    </tr>
  </table>
</div>
<script>
  var xhr = new XMLHttpRequest();
  // 上传失败处理
  function uploadFailed(evt) {
    console.log(evt);
    document.getElementById("progressBar").style.visibility = "hidden";
    document.getElementById("complete").innerText = evt.value();
  }
  // 侦察附件上传情况，这个方法大概0.05-0.1秒执行一次
  function onprogress(evt) {

    document.getElementById("progressBar").style.visibility = "visible";
    var loaded = evt.loaded;    // 已经上传大小情况
    var total = evt.total;  // 附件总大小
    var per = Math.floor(100 * loaded / total); // 已经上传的百分比
    document.getElementById("progressPersent").innerText = per + "%";
    document.getElementById("progress").style.width = per + "%";
  }
  // 上传文件
  function uploadFile() {
    // 1. 将上传的文件放入FormData中
    var fileList = document.getElementById("pic").files;
    var formData = new FormData();
    formData.append("file", fileList[0]);
    formData.append("subjectId",12);
    // 监听事件
    xhr.upload.addEventListener("progress", onprogress, false);
    xhr.addEventListener("error", uploadFailed, false);
    //    请求方式      接口    true：异步请求
    xhr.open("POST", "http://192.168.0.110:8900/lxy/document/uploadDoc", true);
    xhr.send(formData); // 带上数据
    xhr.onreadystatechange = function (ev) {
      if (xhr.readyState == 4 && xhr.status == 200) {
        console.log("---"+xhr.responseText)
        if (xhr.responseText == "success") {
          document.getElementById("progress").style.width = "100%";
          document.getElementById("progressPersent").innerText ="100%" ;
          document.getElementById("complete").innerText ="上传成功！" ;
        }else {
          document.getElementById("complete").innerText ="上传失败！" ;
        }
      }
    }
  }
</script>

</body>
</html>